import util from "../../utils/util";
import answerUtil from "../../utils/answerUtil";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    desc:'',//描述
    isStart:false,//是否开始
    questionIndex:0,//当前题型索引
    totalCount: 0,//题目数量
    topicContent:[],//当前题型所有题目
    currentIndex: 0, // 当前题目索引
    currentTopic: null, // 当前展示的题目
    startTime: 0, //开始时间戳
    timeStr: 0,//页面倒计时
    questionAnswer: 0,//答案
    countdownInterval: null, // 存储 interval ID
    questionStartTime: null,//记录题目开始时间
    answerRecords: [],//答题记录
  },
  onLoad() {
    this.getTopicData();

     // 初始化时加载已有的答题记录
     const savedAnswerRecords = answerUtil.getAnswerRecords();
     this.setData({
       answerRecords: savedAnswerRecords
     });
  },
  getTopicData(){
    const questionIndex = wx.getStorageSync('questionInfo').questionNumber;
    const {count,topicContent} = util.getData(questionIndex);
    this.setData({
      totalCount:count,
      topicContent,
      questionIndex
    })
    this.getCurrentTopicData();
  },
  getCurrentTopicData(){
    const {topicContent,currentIndex} = this.data;
    const currentTopic = topicContent[currentIndex];// 当前展示的题目
    const maxAnswerTime = parseInt(currentTopic.maxAnswerTime, 10) / 1000;
    const questionAnswer = parseInt(currentTopic.standardTime, 10);
    const describe = JSON.parse(currentTopic.describe);
    const desc = describe[0].content;
    this.setData({
      timeStr:maxAnswerTime,
      questionAnswer,
      desc
    })
  },
  onStar() {
    const startTime = Date.now();
    this.setData({
      startTime: startTime,
      isStart:true
    })
    this.startCountdown(); // 添加倒计时
  },
  // 启动倒计时
  startCountdown() {
    const { countdownInterval } = this.data;
    // 清除已有倒计时
    if (countdownInterval) {
      clearInterval(countdownInterval);
    }
    const interval = setInterval(() => {
      this.setData({
        timeStr: this.data.timeStr - 1
      });

      if (this.data.timeStr <= 0) {
        this.handleTimeout(); // 处理超时逻辑
        clearInterval(interval);
      }
    }, 1000);

    this.setData({ countdownInterval: interval });
  },   
  // 超时事件
  handleTimeout() {
    wx.showToast({
      title: '已超时',
      icon: 'none',
      duration: 1000
    });
    
    // 使用共用方法创建并保存答题记录
    const newAnswerRecords = this.createAndSaveAnswerRecord(true);
    this.setData({
      answerRecords: newAnswerRecords
    })

    setTimeout(() => {
      let {currentIndex,totalCount} = this.data;
      // 无论对错都增加总次数
      let countNum = currentIndex + 1;
      if (countNum >= totalCount) {
          //跳转下一题
          let questionNumber = this.data.questionIndex + 1;
          const prevInfo = wx.getStorageSync('questionInfo') || {};
          wx.setStorageSync('questionInfo', {
            ...prevInfo,
            questionNumber
          });
          util.navigateByDesc(questionNumber);
      } else {
        this.getCurrentTopicData()
      }
      this.setData({
        isStart: false,
        currentIndex: countNum,
      })
    }, 1000);
  },
  onStop(){
    let {totalCount,currentIndex,startTime} = this.data;
    if (!startTime) return;
    const endTime = Date.now();
    const elapsed = endTime - startTime; // 答题时间
    // 使用共用方法创建并保存答题记录
    const newAnswerRecords = this.createAndSaveAnswerRecord(false,elapsed);
    this.setData({
      answerRecords: newAnswerRecords
    })
    let countNum = currentIndex + 1;
    if (countNum >= totalCount) {
      //跳转下一题
      let questionNumber = this.data.questionIndex + 1;
      const prevInfo = wx.getStorageSync('questionInfo') || {};
      wx.setStorageSync('questionInfo', {
        ...prevInfo,
        questionNumber
      });
      util.navigateByDesc(questionNumber);
    }else {
      this.getCurrentTopicData()
    }
    this.setData({
      isStart: false,
      startTime: 0,
      currentIndex:countNum
    });
    // 清除倒计时
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({ countdownInterval: null });
    }
  },
  // 处理答题记录
  createAndSaveAnswerRecord(isTimeout = false, userOption = '') {
    const {currentIndex, topicContent, questionAnswer} = this.data;
    
    // 计算答题时间
    const endTime = new Date().getTime();
    // 获取当前题目信息
    const currentTopic = topicContent[currentIndex];
    let answerTime = currentTopic.maxAnswerTime;
    let isRight = 0;
    let option = '';
    
    if (!isTimeout) {
      isRight = 1;
      option = userOption.toString();
      answerTime = userOption
    }
    
    // 创建答题记录
    const answerRecord = answerUtil.createAnswerRecord({
      qosId: currentTopic.questionId,
      anserTime: answerTime,
      isRight: isRight,
      option: option,
      classify: currentTopic.classify,
      stem: currentTopic.stem,
      accuracy: '',
      timeStemp: endTime.toString(),
      everyTxt: '',
      rightOption: questionAnswer,
      score: 0,
    });
    
    // 添加答题记录
    const newAnswerRecords = answerUtil.addAnswerRecord(answerRecord);
    
    return newAnswerRecords;
  },

  onUnload() {
    // 清除倒计时
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({ countdownInterval: null });
    }
    // 页面卸载时确保答题记录已保存
    answerUtil.saveAnswerRecords(this.data.answerRecords);
  }
})